package com.mhc.haval.security.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mhc.haval.security.constant.MsgCodeEnum;
import com.mhc.haval.security.model.User;
import com.mhc.haval.security.util.HtmlUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * custom login success handler
 *
 * @author Churry
 * @create 2017-08-21 14:48
 **/
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    /**
     * 重写登录认证成功的处理方法
     *
     * @param request
     * @param response
     * @param authentication
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        Object principal = authentication.getPrincipal();
        if (principal instanceof User) {
            Map<String, Object> responseMap = new HashMap();
            User userDetail = (User)principal;
            responseMap.put("data", userDetail);
            responseMap.put("success", true);
            responseMap.put("code", MsgCodeEnum.SUCCESS.getErrCode());
            responseMap.put("message", MsgCodeEnum.SUCCESS.getErrMsg());
            responseMap.put("x-auth-token", request.getSession().getId());
            HtmlUtil.writerJson(response, responseMap);
            //获取token
            String token = response.getHeader("x-auth-token");
            logger.info("x-auth-token : " + token);
        }
        super.onAuthenticationSuccess(request, response, authentication);
    }

    /**
     * 去掉数据列表中的创建时间与修改时间
     *
     * @param jsonArray
     * @return
     */
    private JSONArray removeDateInJsonArray(JSONArray jsonArray) {
        JSONArray resultJsonArray = new JSONArray();
        Iterator<Object> it = jsonArray.iterator();
        while (it.hasNext()) {
            JSONObject jsonObject = (JSONObject) it.next();
            jsonObject.remove("gmtModified");
            jsonObject.remove("gmtCreate");
            resultJsonArray.add(jsonObject);
        }
        return resultJsonArray;
    }
}
